package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import jdk.nashorn.internal.ir.CallNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private RedisTemplate redisTemplate;

    //注入service
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;



    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //方法一
        /*Set keys=redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        //方法二
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success();
    }

    @GetMapping("/page")
    public R<Page> page( @RequestParam( required = false , defaultValue = "1") int page ,
                         @RequestParam( required = false , defaultValue = "10") int pageSize ,String name ){
        Page<Dish> pageInfo = new Page(page,pageSize);

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //模糊查询 根据名字查询
        lambdaQueryWrapper.like(name != null , Dish::getName ,name);
        //根据查询的最后时间排序
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,lambdaQueryWrapper);

        //封装数据 total
        Page<DishDto> dishDtoPage = new Page<>();
        dishDtoPage.setTotal(pageInfo.getTotal());

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            //讲dish 中的数据 复制给 dishdto中
            BeanUtils.copyProperties(dish,dishDto);
            //根据ID查询分类对象
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null){
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> update(@PathVariable Long id){
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    @PutMapping
    public R putting(@RequestBody DishDto dishDto){
        log.info("修改菜品信息");
        dishService.updateWithFlavor(dishDto);
        //修改后删除该菜品的全部缓存
        Set keys=redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success();
    }

   /* @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(dish.getCategoryId() != null , Dish::getCategoryId,dish.getCategoryId());
        lambdaQueryWrapper.eq(Dish::getStatus,1);

        //排序
        //lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);


        List<Dish> list = dishService.list(lambdaQueryWrapper);

        return R.success(list);
    }*/

   @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){



       //动态获取key
       String key = "dish_"+dish.getCategoryId() +"_1";
       List<DishDto> dtoList=(List<DishDto>) redisTemplate.opsForValue().get(key);
       if (!CollectionUtils.isEmpty(dtoList)){
           log.info("查询到结果了可以直接返回");
           return R.success(dtoList);
       }

       LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询当前菜id
       lambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //判断起售的菜
       lambdaQueryWrapper.eq(Dish::getStatus,1);
        //排序
       lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
       //遍历菜品
       List<Dish> dishList = dishService.list(lambdaQueryWrapper);

       List<DishDto> dishDtoList = dishList.stream().map(dish1 -> {
           //此时的dish1 是 Dish 的数据  要把他复制给DishDto 中 用DishDto来查

           //封装CategoryName
           DishDto dishDto = new DishDto();
           //复制
           BeanUtils.copyProperties(dish1, dishDto);
           //查一下当前菜品对应的种类名字
           Long categoryId = dishDto.getCategoryId();
           Category category = categoryService.getById(categoryId);
           if (category != null) {
               //查到了当前菜品种类
               //要给dishDto中的菜品种类给一个名字
               String name = category.getName();
               dishDto.setCategoryName(name);
           }

           //封装口味
           LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
           //获得口味id
           flavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
           List<DishFlavor> list = dishFlavorService.list(flavorLambdaQueryWrapper);

           //讲查询出来的set给DishDto
           dishDto.setFlavors(list);
           return dishDto;

       }).collect(Collectors.toList());
       redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
       log.info("没有查询到结果 先访问数据库 然后将结果给redis");
       return R.success(dishDtoList);
   }

   @PostMapping("/status/{status}")
    public R post(@PathVariable int status ,@RequestParam List<Long> ids){

       if (status == 1){
           //批量起售
           LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
           queryWrapper.in(Dish::getId,ids);
           //找到dish
           List<Dish> list = dishService.list(queryWrapper);
           for (Dish dish : list) {
               dish.setStatus(1);
           }
           dishService.updateBatchById(list);
           return R.success();
       }

       if (status == 0){
           //批量禁售
           LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
           queryWrapper.eq(SetmealDish::getDishId,ids);
           int count = setmealDishService.count(queryWrapper);
           if (count > 0 ){
               //在售商品不能禁售
               throw new CustomException("包含了在售商品 不能禁售");
           }else{
               LambdaQueryWrapper<Dish> queryWrappe1 = new LambdaQueryWrapper<>();
               queryWrappe1.in(Dish::getId,ids);
               List<Dish> dishList = dishService.list(queryWrappe1);
               for (Dish dish : dishList) {
                   dish.setStatus(0);
               }
               dishService.updateBatchById(dishList);
               return R.success();
           }

       }

       return R.success();

   }

   @DeleteMapping()
   public R delete(@RequestParam  List<Long> ids){
       LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.in(Dish::getId,ids);
       queryWrapper.eq(Dish::getStatus,1);

       int count = dishService.count(queryWrapper);
       if (count > 0){
           //不能删
           throw new CustomException("该菜品为起售不能删除");
           //return R.error("不能删除 状态为起售");
       }

       dishService.deleteWithSetmeal(ids);

       Set keys=redisTemplate.keys("dish_*");
       redisTemplate.delete(keys);

       return R.success();
   }
}
